import { AccountBookOutlined, CheckOutlined, EditOutlined, EllipsisOutlined, FileOutlined, MoneyCollectOutlined, PayCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { Button, Divider, InputNumber, message, Switch, Tooltip } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { SwitchTheme, ThemeType } from '../App';
import useTrigger from '../hooks/useTrigger';
import { BudgetExhibit } from '../interface/budgetData';
import { DarkModeActivated, DarkModeDeactivated } from '../redux/Global/action';
import { BudgetDataSelector, DarkModeSelector } from '../redux/Global/selector';
import { ActionProps } from '../redux/type';
import FormatNumber from '../util/formatNumber';
import { Sleep } from '../util/sleep';
import AddRecordModal from './Panel/AddRecordModal';

export interface HeaderContext
{
    setIsOpenAddBudgetModal: Function;
    defaultTabIndex: string;
}


export default function Header()
{
    const budgetData: BudgetExhibit[] = useSelector(BudgetDataSelector);

    const isDarkMode = useSelector(DarkModeSelector);

    const dispatch = useDispatch();

    const [isOpenAddBudgetModal, setIsOpenAddBudgetModal] = useTrigger(false);

    //设置默认打开的Tab
    const [defaultTabIndex, setDefaultTabIndex] = useState<string>('1');

    //将设置打开Modal框的方法共享一下
    const IsOpenAddBudgetModalContext = React.createContext<HeaderContext>({ setIsOpenAddBudgetModal, defaultTabIndex });

    //设置编辑总金额状态
    const [editTotalAmount, setEditTotalAmount] = useTrigger(false);

    //设置编辑总金额提交时按钮等待
    const [postTotalAmountLoading, setPostTotalAmountLoading] = useTrigger(false);

    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() =>
    {
        if (isDarkMode)
        {
            SwitchTheme(ThemeType.DarkTheme);
        } else
        {
            SwitchTheme(ThemeType.DefaultTheme);
        }
    }, [isDarkMode]);

    useEffect(() =>
    {
        dispatch({ type: 'SelectBudgetExhibitData' });
    }, [dispatch]);

    return (
        <div className='Header'>
            <div className='TotalAmountAndOptions'>
                <div className='TotalAmount'>
                    {
                        editTotalAmount
                            ? <InputNumber
                                ref={inputRef}
                                prefix="￥"
                                size='large'
                                defaultValue={budgetData[0].totalAmount}
                                style={{ width: '200px' }}
                            />
                            : <h1>&yen;{FormatNumber(budgetData[0]?.totalAmount ?? 0)}</h1>
                    }
                    {!editTotalAmount && <span>总资产(元) </span>}
                    <Button
                        style={{ alignSelf: "center" }}
                        size='large'
                        icon={editTotalAmount ? <CheckOutlined /> : <EditOutlined />}
                        type='link'
                        loading={postTotalAmountLoading}
                        onClick={async (e) =>
                        {
                            if (editTotalAmount)
                            {
                                setPostTotalAmountLoading(true);
                                const { value } = inputRef.current as HTMLInputElement;
                                if (value)
                                {
                                    dispatch<ActionProps<string, string>>({
                                        type: 'UpdateTotalAmount', payload: value
                                    });
                                    await Sleep(500);
                                    dispatch({ type: 'SelectBudgetExhibitData' });
                                } else
                                {
                                    message.error('出错了,请稍后再试');
                                }
                                setPostTotalAmountLoading(false);
                            }
                            setEditTotalAmount(!editTotalAmount);
                        }} />
                </div>
                <div className='Options'>
                    <Tooltip title='刷新'>

                        <Button icon={<ReloadOutlined />} loading={postTotalAmountLoading}
                            onClick={e =>
                            {
                                setPostTotalAmountLoading(true);
                                dispatch({ type: 'SelectBudgetExhibitData' });
                                Sleep(500);
                                setPostTotalAmountLoading(false);
                            }} />
                    </Tooltip>
                    <Button icon={<FileOutlined />} />
                    <Button icon={<EllipsisOutlined />} />
                    <Switch checked={isDarkMode} checkedChildren="🌛" unCheckedChildren="🌞" defaultChecked onClick={() =>
                    {
                        isDarkMode
                            ? dispatch(DarkModeDeactivated())
                            : dispatch(DarkModeActivated());
                    }} />
                </div>
            </div>
            <div className='TimeAndAddButton'>
                <Today />
                <Divider type='vertical' />
                <Button type='link' children="收入" style={{ color: '#52c41a' }} icon={<MoneyCollectOutlined />}
                    onClick={e =>
                    {
                        setIsOpenAddBudgetModal(true);
                        setDefaultTabIndex('INCOME');
                    }} />
                <Divider type='vertical' />
                <Button type='link' children="支出" style={{ color: '#f5222d' }} icon={<PayCircleOutlined />}
                    onClick={e =>
                    {
                        setIsOpenAddBudgetModal(true);
                        setDefaultTabIndex('EXPENSES');
                    }} />
                <Divider type='vertical' />
                <Button type='link' children="预算" icon={<AccountBookOutlined />} />
            </div>
            <Divider dashed />
            <IsOpenAddBudgetModalContext.Provider value={{
                setIsOpenAddBudgetModal,
                defaultTabIndex,
            }}>
                <AddRecordModal
                    isOpen={isOpenAddBudgetModal}
                    IsOpenAddBudgetModalContext={IsOpenAddBudgetModalContext}
                />
            </IsOpenAddBudgetModalContext.Provider>
        </div>
    );
}



function Today()
{
    const [today, setToday] = useState<string>(moment(Date.now()).format("YYYY年MM月DD日 hh:mm:ss"));

    useEffect(() =>
    {
        setInterval(() =>
        {
            setToday((prveValue: string) =>
            {
                return moment(Date.now()).format("YYYY年MM月DD日 hh:mm:ss");
            });
        }, 1000);
    }, [today]);
    return (
        <div>
            {today}
        </div>
    );
}
